﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using Microsoft.Win32;
using ShapeConnectors.MaTrix;

using System.Collections.Generic;
using System;
namespace ShapeConnectors
{
    public partial class Window1 : Window
    {
        // flag for enabling "New thumb" mode
        bool isAddNewAction = false;
        // flag for enabling "New link" mode
        bool isAddNewLink = false;
        // flag that indicates that the link drawing with a mouse started
        bool isLinkStarted = false;
        // variable to hold the thumb drawing started from
        MyThumb linkedThumb;//đỉnh
        // Line drawn by the mouse before connection established
        LineGeometry link;//1 đường dẫn từ a->b

        List<MyThumb> dsDinh=new List<MyThumb>();
        List<LineGeometry> dsCanh = new List<LineGeometry>();


        public Window1()
        {
            InitializeComponent();            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Setup connections for predefined thumbs            
            
            //xử lý cho phép đặt 1 đỉnh mới
            this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonDown);
            //hiện đường kéo chuột
            this.PreviewMouseMove += new MouseEventHandler(Window1_PreviewMouseMove);
            //xử lý cho nét vẽ đến có thể nhấp vào đỉnh kết thúc
            this.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(Window1_PreviewMouseLeftButtonUp);

            this.Title = "Links established: " + connectors.Children.Count.ToString();
        }

        // Event hanlder for dragging functionality support
        //hàm di di chuyen dinh trên form
        private void onDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            // Exit dragging operation during adding new link
            if (isAddNewLink) return;

            MyThumb thumb = e.Source as MyThumb;//xac dinh 1 đỉnh đang chọn

            Canvas.SetLeft(thumb, Canvas.GetLeft(thumb) + e.HorizontalChange);//cập nhật lại tọa độ đan xét
            Canvas.SetTop(thumb, Canvas.GetTop(thumb) + e.VerticalChange);
             
            // Update links' layouts for active thumb
            thumb.UpdateLinks();//cập nhật lại danh sách các line nối với đỉnh đó
        }
        void taodinh(int i,Point p)
        {
            MyThumb newThumb = new MyThumb(
            Application.Current.Resources["BasicShape1"] as ControlTemplate,
            i.ToString(),
            "/Images/gear_connection.png",
            p,//tọa độ của chuột là tọa độ của đỉnh,
            onDragDelta);
            myCanvas.Children.Add(newThumb);
            dsDinh.Add(newThumb);
        }
        void taocanh()
        {
            for(int i=0;i<MaTran.spt;i++)
                for (int j = i+1; j < MaTran.spt; j++)
                {
                    if (MaTran.a[i, j] != 0)
                    {
                        link = new LineGeometry(dsDinh[i].P,dsDinh[j].P);
                        dsDinh[i].LinkTo(dsDinh[j], link);
                        dsCanh.Add(link);
                        connectors.Children.Add(link);
                    }
                }
        }
        // Event handler for creating new thumb element by left mouse click
        // and visually connecting it to the myThumb2 element
        
        void Window1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // If adding new action...
            if (isAddNewAction)
            {
                // Create new thumb object based on a static template "BasicShape1"
                // specifying thumb text as "action" and icon as "/Images/gear_connection.png"
               
                MyThumb newThumb = new MyThumb(
                    Application.Current.Resources["BasicShape1"] as ControlTemplate,
                    "action",
                    "/Images/gear_connection.png",
                    e.GetPosition(this),//tọa độ của chuột là tọa độ của đỉnh,
                    onDragDelta);//xét sự kiện di chuyển cho đỉnh đang tạo);  //tạo mới 1 đỉnh              
                dsDinh.Add(newThumb);
                // Put newly created thumb on the canvas
                myCanvas.Children.Add(newThumb);
                
                // resume common layout for application
                isAddNewAction = false;                
                Mouse.OverrideCursor = null;
                btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
                e.Handled = true;
            }

            // Is adding new link and a thumb object is clicked...
            //tạo đường dẫn 2 đỉnh bằng chuột
            if (isAddNewLink && e.Source.GetType() == typeof(MyThumb))//e.Source.GetType() là xác định dc đỉnh đang click
            {                
                if (!isLinkStarted)
                {
                    if (link == null || link.EndPoint != link.StartPoint)
                    {
                        Point position = e.GetPosition(this);//lấy tọa độ chuột
                        link = new LineGeometry(position, position);//khi bắt đầu nhấp vào đỉnh để tạo cạnh thì tọa độ đầu và cuối là như nhau
                        connectors.Children.Add(link);//chứa link 
                        isLinkStarted = true;
                        linkedThumb = e.Source as MyThumb;
                        e.Handled = true;
                    }
                }
            }
        }

        // Handles the mouse move event when dragging/drawing the new connection link
        void Window1_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (isAddNewLink && isLinkStarted)
            {
                // Set the new link end point to current mouse position
                link.EndPoint = e.GetPosition(this);//đỉnh kết thúc thay đổi
                e.Handled = true;
            }
        }

        // Handles the mouse up event applying the new connection link or resetting it
        void Window1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            // If "Add link" mode enabled and line drawing started (line placed to canvas)
            if (isAddNewLink && isLinkStarted)
            {
                // declare the linking state
                bool linked = false;
                // We released the button on MyThumb object
                if (e.Source.GetType() == typeof(MyThumb))
                {
                    MyThumb targetThumb = e.Source as MyThumb;
                    // define the final endpoint of line
                    link.EndPoint = e.GetPosition(this);
                    // if any line was drawn (avoid just clicking on the thumb)
                    if (link.EndPoint != link.StartPoint && linkedThumb != targetThumb)
                    {
                        // establish connection
                        linkedThumb.LinkTo(targetThumb, link);//nối 2 đỉnh
                        dsCanh.Add(link);
                        // set linked state to true
                        linked = true;
                    }
                }
                // if we didn't manage to approve the linking state
                // button is not released on MyThumb object or double-clicking was performed
                if (!linked)
                {
                    // remove line from the canvas
                    connectors.Children.Remove(link);
                    // clear the link variable
                    link = null;
                }
                
                // exit link drawing mode
                isLinkStarted = isAddNewLink = false;
                // configure GUI
                btnNewAction.IsEnabled = btnNewLink.IsEnabled = true;
                Mouse.OverrideCursor = null;
                e.Handled = true;
            }
            this.Title = "Links established: " + connectors.Children.Count.ToString();
        }
        
        // Event handler for enabling new thumb creation by left mouse button click
        private void btnNewAction_Click(object sender, RoutedEventArgs e)
        {            
            isAddNewAction = true;
            Mouse.OverrideCursor = Cursors.SizeAll;//doi kieu chuot
            btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;//button chìm xuống
        }

        private void btnNewLink_Click(object sender, RoutedEventArgs e)
        {
            isAddNewLink = true;
            Mouse.OverrideCursor = Cursors.Cross;
            btnNewAction.IsEnabled = btnNewLink.IsEnabled = false;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text|*.txt|All File()|*.*";
            ofd.Title = "Open File...";
            if (ofd.ShowDialog() == true)
            {
                MaTran.Docfile(ofd.FileName);

            }
            //float radius = 0.017453293f;
            Point p = new Point();
            float   goc = (float)(360 / MaTran.spt);
            for (int i = 0; i < MaTran.spt; i++)
            {

                p.X = 0;
                p.Y = 0;
                taodinh(i, p);
            }
            taocanh();

            
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            MaTran.PhatSinh();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog ofd = new SaveFileDialog();
            ofd.Filter = "Text|*.txt|All File()|*.*";
            ofd.Title = "Save File...";
            if (ofd.ShowDialog() == true)
            {
                MaTran.Ghifile(ofd.FileName);

            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
           
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            while(dsDinh.Count!=0)
            {
                myCanvas.Children.Remove(dsDinh[0]) ;
                dsDinh.RemoveAt(0);
            }
            while (dsCanh.Count != 0)
            {
                connectors.Children.Remove(dsCanh[0]);
                dsCanh.RemoveAt(0);
            }
            //MyThumb newThumb = new MyThumb();
            //newThumb
            //myCanvas.Children.Add(newThumb);
            ////for (int i = 0; i < MaTran.spt; i++)
            ////{

            ////}
        }
   
    }
}
